package com.itheima.service.db.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.domain.db.AnalysisByDay;
import com.itheima.mapper.AnalysisByDayMapper;
import com.itheima.mapper.LogMapper;
import com.itheima.service.db.AnalysisByDayService;
import com.itheima.util.ComputeUtil;
import com.itheima.vo.AnalysisSummaryVo;
import com.itheima.vo.DashboardVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@DubboService
public class AnalysisByDayServiceImpl implements AnalysisByDayService {

    @Autowired
    AnalysisByDayMapper analysisByDayMapper;

    @Autowired
    LogMapper logMapper;

    @Override
    public void saveOrUpdate() {
        //0.准备数据(今天,昨天)
        String today = DateUtil.offsetDay(new Date(), 0).toDateStr();//2022-11-08
        String yesterday = DateUtil.offsetDay(new Date(), -1).toDateStr();//2022-11-07

        //1.查询今天有无记录
        LambdaQueryWrapper<AnalysisByDay> qw = new LambdaQueryWrapper<>();
        qw.eq(AnalysisByDay::getRecordDate,today);
        AnalysisByDay analysisByDay = analysisByDayMapper.selectOne(qw);

        if (analysisByDay == null) {
            //2.若无记录,封装对象,往表中存放记录
            analysisByDay = new AnalysisByDay();
            analysisByDay.setRecordDate(new Date());
            analysisByDay.setNumRegistered(logMapper.findRegisterOrLoginCount(today,"0102"));
            analysisByDay.setNumActive(logMapper.findActiveCount(today));
            analysisByDay.setNumLogin(logMapper.findRegisterOrLoginCount(today,"0101"));
            analysisByDay.setNumRetention1d(logMapper.findRetention1d(today,yesterday));

            analysisByDayMapper.insert(analysisByDay);
        }else{
            //3.若有记录,封装对象,往表中更新记录
            analysisByDay.setNumRegistered(logMapper.findRegisterOrLoginCount(today,"0102"));
            analysisByDay.setNumActive(logMapper.findActiveCount(today));
            analysisByDay.setNumLogin(logMapper.findRegisterOrLoginCount(today,"0101"));
            analysisByDay.setNumRetention1d(logMapper.findRetention1d(today,yesterday));

            analysisByDayMapper.updateById(analysisByDay);
        }
    }

    @Override
    public AnalysisSummaryVo findSummary() {
        //1.准备数据
        Date date = new Date();
        String today = DateUtil.offsetDay(date, 0).toDateStr();
        String yesterday = DateUtil.offsetDay(date, -1).toDateStr();
        //过去7天
        String passWeek = DateUtil.offsetDay(date, -7).toDateStr();
        //过去1月
        String passMonth = DateUtil.offsetDay(date, -30).toDateStr();
        //获取今天的数据
        AnalysisByDay todayAnalysis = analysisByDayMapper.findByRecordDate(today);
        //获取昨天的数据
        AnalysisByDay yesterdayAnalysis = analysisByDayMapper.findByRecordDate(yesterday);

        //2.创建vo
        AnalysisSummaryVo vo = new AnalysisSummaryVo();

        //3.封装vo中9个数据
        //累计用户数 cumulativeUsers;
        vo.setCumulativeUsers(analysisByDayMapper.findUserTotalCount());

        //过去30天活跃用户数 activePassMonth;
        vo.setActivePassMonth(analysisByDayMapper.findActiveUserCountInPeriod(passMonth,yesterday));
        //过去7天活跃用户 activePassWeek;
        vo.setActivePassWeek(analysisByDayMapper.findActiveUserCountInPeriod(passWeek,yesterday));
        //今日新增用户数量  newUsersToday;
        vo.setNewUsersToday(todayAnalysis.getNumRegistered().longValue());
        //今日新增用户涨跌率，单位百分数，正数为涨，负数为跌    newUsersTodayRate;
        vo.setNewUsersTodayRate(ComputeUtil.computeRate(todayAnalysis.getNumRegistered(), yesterdayAnalysis.getNumRegistered()));
        //今日登录次数 loginTimesToday;
        vo.setLoginTimesToday(todayAnalysis.getNumLogin().longValue());
        //今日登录次数涨跌率，  loginTimesTodayRate;
        vo.setLoginTimesTodayRate(ComputeUtil.computeRate(todayAnalysis.getNumLogin(),yesterdayAnalysis.getNumLogin()));
        //今日活跃用户数量 activeUsersToday;
        vo.setActiveUsersToday(todayAnalysis.getNumActive().longValue());
        //今日活跃用户涨跌率， activeUsersTodayRate;
        vo.setActiveUsersTodayRate(ComputeUtil.computeRate(todayAnalysis.getNumActive(), yesterdayAnalysis.getNumActive()));

        //4.返回vo
        return vo;
    }

    // 主页展示新增、活跃用户、次日留存率折线图
    @Override
    public List<DashboardVo> findDashboardVo(Long startTime, Long endTime, String type) {
        // 算出最后一天
        String endDay = DateUtil.offsetDay(new Date(endTime), 0).toDateStr();
        // 声明一个集合
        List<DashboardVo> dashboardVos = new ArrayList<>();
        // 声明一个常量
        Integer day = 0;
        // 进行循环操作
        while (!endDay.equals(DateUtil.offsetDay(new Date(startTime), day).toDateStr())) {
            // 声明对象
            DashboardVo dashboardVo = new DashboardVo();
            // 算出当前天数
            String startDay = DateUtil.offsetDay(new Date(startTime), day).toDateStr();
            day++;
            // 创建条件
            QueryWrapper<AnalysisByDay> qw = new QueryWrapper<>();
            qw.eq("record_date", startDay);
            qw.orderByDesc("created");
            // 查询数据库
            List<AnalysisByDay> analysisByDays = analysisByDayMapper.selectList(qw);
            // 判空并去第一个
            if (CollectionUtil.isNotEmpty(analysisByDays)) {
                AnalysisByDay analysisByDay = analysisByDays.get(0);
                // type选择
                switch (type) {
                    case "101": // 注册
                        dashboardVo.setAmount(analysisByDay.getNumRegistered());
                        break;
                    case "102":  // 活跃
                        dashboardVo.setAmount(analysisByDay.getNumActive());
                        break;
                    case "103":  // 次日登录
                        dashboardVo.setAmount(analysisByDay.getNumRetention1d());
                        break;
                }
            } else { // 没有数据都为0
                dashboardVo.setAmount(0);
            }
            // 封装时间
            dashboardVo.setTitle(startDay);
            // 添加到集合中
            dashboardVos.add(dashboardVo);
        }
        return dashboardVos;
    }
}
